package com.sense.cloud.coreservice.sdk.auth.utils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Properties;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import com.sense.cloud.coreservice.sdk.auth.utils.http.HttpClientConnectionManagerWrapper;

public class SdkPropUtilLoadUrl {
	private static Properties prop = new Properties();

	static {
		Properties prop = new Properties();
		try {
			byte[] bs = get();
			InputStream bis = new ByteArrayInputStream(bs);
			prop.load(bis);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private SdkPropUtilLoadUrl() {
	}

	public static String getStr(String key, String defultVal) {
		String val = prop.getProperty(key);
		if (val == null || val.length() == 0) {
			val = defultVal;
		}
		return val;
	}

	public static Integer getInt(String key, Integer defultVal) {
		String val = prop.getProperty(key);
		Integer intval = defultVal;
		if (val != null && val.length() > 0) {
			intval = Integer.parseInt(val);
		}
		return intval;
	}

	private static byte[] get() throws Exception {
		CloseableHttpClient httpClient = HttpClientConnectionManagerWrapper.getHttpClient();
		CloseableHttpResponse response = null;
		HttpGet httpReq = null;
		try {
			String s_accesskey = LoadConfigService.getAccessKey();
			String s_secret = LoadConfigService.getSecret();
			String s_nonce = (int) Math.random() * 1000 + "";
			String url = SdkPropUtil.getStr("auth.server", "http://127.0.0.1:8080/auth/getConfig.do");
			// 设置url和参数
			StringBuilder paramSb = new StringBuilder("?");
			paramSb.append("s_accesskey").append("=").append(s_accesskey).append("&");
			paramSb.append("s_nonce").append("=").append(s_nonce).append("&");

			String signStr = getAction(url) + paramSb.toString() + "s_secret=" + s_secret;
			String s_sign = MD5Utils.md5(signStr);
			paramSb.append("s_sign").append("=").append(s_sign);
			httpReq = new HttpGet(url + paramSb.toString());
			// 配置连接超时等属性
			RequestConfig config = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build();
			httpReq.setConfig(config);

			// request
			response = httpClient.execute(httpReq);

			if (response.getStatusLine().getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				return EntityUtils.toByteArray(entity);
			} else {
				// 返回非200状态码的时候也应消费掉消息，以确保内部流被关闭
				HttpEntity entity = response.getEntity();
				EntityUtils.consume(entity);
				throw new Exception("http request failed, status code:" + response.getStatusLine().getStatusCode());
			}
		} catch (Exception e) {
			throw e;
		} finally {
			if (httpReq != null) {
				httpReq.releaseConnection();
			}
			try {
				if (response != null) {
					response.close();
				}
			} catch (Exception e2) {
			}
		}
	}

	private static String getAction(String url) {
		int j = url.indexOf("//");
		int i = url.indexOf("/", j + 2);

		String action = url.substring(i, url.length());
		int k = url.indexOf("?");
		if (k > 0) {
			action = url.substring(i, k);
		}
		return action;
	}
}
